'use client';

import { useState, useRef } from 'react';
import { CarMediaUpload as CarMediaUploadType, MediaType, MediaCategory } from '@/types';
import UploadService from '@/services/upload.service';

interface CarMediaUploadProps {
  onMediaChange: (media: CarMediaUploadType[]) => void;
  maxFiles?: number;
}

export default function CarMediaUpload({ onMediaChange, maxFiles = 20 }: CarMediaUploadProps) {
  const [mediaFiles, setMediaFiles] = useState<CarMediaUploadType[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files) return;

    const newMediaFiles: CarMediaUploadType[] = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      
      // 检查文件类型
      const isImage = file.type.startsWith('image/');
      const isVideo = file.type.startsWith('video/');
      
      if (!isImage && !isVideo) {
        alert('只支持图片和视频文件');
        continue;
      }

      // 检查文件大小
      if (file.size > 50 * 1024 * 1024) { // 50MB
        alert(`文件 ${file.name} 大小超过限制 (50MB)`);
        continue;
      }

      // 检查总数限制
      if (mediaFiles.length + newMediaFiles.length >= maxFiles) {
        alert(`最多只能上传 ${maxFiles} 个文件`);
        break;
      }

      const mediaFile: CarMediaUploadType = {
        file,
        type: isImage ? MediaType.IMAGE : MediaType.VIDEO,
        category: MediaCategory.EXTERIOR, // 默认外观
        previewUrl: UploadService.getFilePreviewUrl(file),
        uploadProgress: 0,
        isUploading: false,
      };

      newMediaFiles.push(mediaFile);
    }

    if (newMediaFiles.length > 0) {
      const updatedMedia = [...mediaFiles, ...newMediaFiles];
      setMediaFiles(updatedMedia);
      onMediaChange(updatedMedia);
    }

    // 重置文件输入
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleCategoryChange = (index: number, category: MediaCategory) => {
    const updatedMedia = [...mediaFiles];
    updatedMedia[index].category = category;
    setMediaFiles(updatedMedia);
    onMediaChange(updatedMedia);
  };

  const handleRemoveFile = (index: number) => {
    const updatedMedia = [...mediaFiles];
    const removedFile = updatedMedia[index];
    
    // 清理预览URL
    if (removedFile.previewUrl) {
      UploadService.revokePreviewUrl(removedFile.previewUrl);
    }
    
    updatedMedia.splice(index, 1);
    setMediaFiles(updatedMedia);
    onMediaChange(updatedMedia);
  };

  const handleUpload = async (index: number) => {
    const updatedMedia = [...mediaFiles];
    const mediaFile = updatedMedia[index];
    
    if (mediaFile.isUploading) return;
    
    mediaFile.isUploading = true;
    mediaFile.uploadProgress = 0;
    setMediaFiles(updatedMedia);
    
    try {
      const response = await UploadService.uploadFile(
        mediaFile.file,
        mediaFile.type === MediaType.IMAGE ? 'image' : 'video',
        (progress) => {
          const updatedMediaProgress = [...mediaFiles];
          updatedMediaProgress[index].uploadProgress = progress;
          setMediaFiles(updatedMediaProgress);
        }
      );
      
      mediaFile.url = response.data.url || response.data.key;
      mediaFile.isUploading = false;
      mediaFile.uploadProgress = 100;
      setMediaFiles(updatedMedia);
      onMediaChange(updatedMedia);
      
    } catch (error) {
      mediaFile.isUploading = false;
      mediaFile.error = '上传失败';
      setMediaFiles(updatedMedia);
      onMediaChange(updatedMedia);
    }
  };

  const handleUploadAll = async () => {
    for (let i = 0; i < mediaFiles.length; i++) {
      if (!mediaFiles[i].url && !mediaFiles[i].isUploading) {
        await handleUpload(i);
      }
    }
  };

  const getCategoryName = (category: MediaCategory) => {
    return category === MediaCategory.EXTERIOR ? '外观' : '内饰';
  };

  const getTypeName = (type: MediaType) => {
    return type === MediaType.IMAGE ? '图片' : '视频';
  };

  return (
    <div className="space-y-4">
      {/* 文件选择区域 */}
      <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center">
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept="image/*,video/*"
          onChange={handleFileSelect}
          className="hidden"
        />
        <button
          type="button"
          onClick={() => fileInputRef.current?.click()}
          className="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700"
        >
          选择文件
        </button>
        <p className="mt-2 text-sm text-gray-500">
          支持图片和视频文件，单个文件最大50MB
        </p>
        <p className="text-xs text-gray-400">
          已选择 {mediaFiles.length} / {maxFiles} 个文件
        </p>
      </div>

      {/* 文件列表 */}
      {mediaFiles.length > 0 && (
        <div className="space-y-3">
          <div className="flex justify-between items-center">
            <h4 className="font-medium text-gray-700">已选文件</h4>
            <button
              type="button"
              onClick={handleUploadAll}
              className="bg-green-600 text-white px-4 py-1 rounded text-sm hover:bg-green-700"
            >
              全部上传
            </button>
          </div>
          
          {mediaFiles.map((media, index) => (
            <div key={index} className="border rounded-lg p-3 bg-gray-50">
              <div className="flex items-center gap-3">
                {/* 预览 */}
                {media.type === 1 ? (
                  <img
                    src={media.previewUrl}
                    alt={media.file.name}
                    className="w-16 h-16 object-cover rounded"
                  />
                ) : (
                  <div className="w-16 h-16 bg-gray-200 rounded flex items-center justify-center">
                    <span className="text-gray-500">视频</span>
                  </div>
                )}
                
                {/* 文件信息 */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="font-medium truncate">{media.file.name}</span>
                    <span className={`px-2 py-1 rounded text-xs ${
                      media.type === 1 ? 'bg-blue-100 text-blue-800' : 'bg-purple-100 text-purple-800'
                    }`}>
                      {getTypeName(media.type)}
                    </span>
                    <span className="text-xs text-gray-500">
                      {(media.file.size / 1024 / 1024).toFixed(1)}MB
                    </span>
                  </div>
                  
                  {/* 分类选择 */}
                  <div className="flex items-center gap-2 mb-2">
                    <span className="text-sm text-gray-600">分类:</span>
                    <select
                      value={media.category}
                      onChange={(e) => handleCategoryChange(index, parseInt(e.target.value) as 1 | 2)}
                      className="text-sm border rounded px-2 py-1"
                    >
                      <option value={1}>外观</option>
                      <option value={2}>内饰</option>
                    </select>
                  </div>
                  
                  {/* 上传状态 */}
                  <div className="flex items-center gap-2">
                    {media.url ? (
                      <span className="text-green-600 text-sm">✓ 已上传</span>
                    ) : media.isUploading ? (
                      <div className="flex items-center gap-2">
                        <div className="w-16 bg-gray-200 rounded-full h-2">
                          <div 
                            className="bg-blue-600 h-2 rounded-full transition-all"
                            style={{ width: `${media.uploadProgress}%` }}
                          ></div>
                        </div>
                        <span className="text-sm text-gray-600">{media.uploadProgress}%</span>
                      </div>
                    ) : (
                      <button
                        type="button"
                        onClick={() => handleUpload(index)}
                        className="bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700"
                      >
                        上传
                      </button>
                    )}
                    
                    {media.error && (
                      <span className="text-red-600 text-sm">{media.error}</span>
                    )}
                  </div>
                </div>
                
                {/* 删除按钮 */}
                <button
                  type="button"
                  onClick={() => handleRemoveFile(index)}
                  className="text-red-600 hover:text-red-800 p-1"
                >
                  ×
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}